Page({
  data: {
    avatar: '',
    nickName: '',
  },
  onLoad() {
    const userinfo = getApp().userinfo
    this.setData({ ...userinfo })
  },
  onNickNameChange(ev) {
    const nickName = ev.detail.value
    nickName && this.updateNickName(nickName)
  },
  onAvatarChange(ev) {
    const avatarUrl = ev.detail.avatarUrl
    avatarUrl && this.updateAvatar(avatarUrl)
  },
  updateAvatar(avatarUrl) {
    // 上传用户头像
    const wxUploaFile = wx.utils.createWxPromiseFun(wx.uploadFile)
    wxUploaFile({
      filePath: avatarUrl,
      name: 'file',
      url: wx.http.baseURL + '/upload',
      header: {
        Authorization: `Bearer ${getApp().token}`,
      },
      formData: {
        type: 'avatar',
      },
    }).then((res) => {
      const data = JSON.parse(res.data)
      this.setData({ avatar: data.data.url })
    })
  },
  // 专门用来更新用户的昵称
  async updateNickName(nickName) {
    const res = await wx.http.put('/userInfo', { nickName })
    if (res.code !== 10000) wx.utils.toast()
  },
})
